import {asyncRouterMap, constantRouterMap} from "../../routes";
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.indexOf(role) >= 0)
    } else {
        return true
    }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
    const accessedRouters = asyncRouterMap.filter(route => {
        if (hasPermission(roles, route)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, roles)
            }
            return true
        }
        return false
    })

    return accessedRouters
}

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: [],
        permissionRouters: [],
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers;
            state.routers = constantRouterMap.concat(routers);
            state.permissionRouters = constantRouterMap.concat(state.addRouters)

        },
        REMOVE_ROUTERS: (state) =>{
            state.routers = []
            state.permissionRouters = []
        }
    },
    actions: {

        GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
                const { roles } = data
                let accessedRouters
                if (roles.indexOf('admin') >= 0 || roles.indexOf("super_editor") >= 0) {
                    accessedRouters = asyncRouterMap
                } else {
                    accessedRouters = filterAsyncRouter(asyncRouterMap, roles)

                }
                console.log("router--->", accessedRouters)
                commit('SET_ROUTERS', accessedRouters)
                resolve()
            })
        },

        removeRoutes({commit}){

            commit("REMOVE_ROUTERS")
        },

        newRoutes ({commit}, role) {
            //  通过递归路由表，删除掉没有权限的路由
            function eachSelect (routers, userRole) {
                for (let j = 0; j < routers.length; j++) {
                    if (routers[j].meta && routers[j].meta.role.length && routers[j].meta.role.indexOf(userRole) === -1) {
                        // 如果没有权限就删除该路由，如果是父级路由没权限，所有子菜单就更没权限了，所以一并删除
                        routers.splice(j, 1)
                        j = j !== 0 ? j - 1 : j // 删除掉没有权限的路由后，下标应该停止 +1，保持不变，如果下标是 0的话删除之后依然等于0
                    }
                    if (routers[j].children && routers[j].children.length) {
                        //  如果包含子元素就递归执行
                        eachSelect(routers[j].children, userRole)
                    }
                }
            }
            // 拷贝这个数组是因为做权限测试的时候可以从低级切回到高级角色，仅限演示，正式开发时省略这步直接使用 addRouter
            // 仅限演示
            let newArr = [...addRouter]
            eachSelect(newArr, role)
            commit('SET_ROUTERS', newArr)

            // 正式开发
            // eachSelect(addRouter, role)
            // commit('setRouters', addRouter)
        },

        /*GenerateRoutes({ commit }, data) {
            return new Promise(resolve => {
                const { roles } = data;
                const accessedRouters = asyncRouterMap.filter(v => {
                    if (roles.indexOf('admin') >= 0) return true;
                    if (hasPermission(roles, v)) {
                        if (v.children && v.children.length > 0) {
                            v.children = v.children.filter(child => {
                                if (hasPermission(roles, child)) {
                                    return child
                                }
                                return false;
                            });
                            return v
                        } else {
                            return v
                        }
                    }
                    return false;
                });
                commit('SET_ROUTERS', accessedRouters);
                resolve();
            })
        }*/
    }
};

export default permission;
